/**
 * Copyright (c) 2020 wuchenxi
 * walter-blog is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 * <p>
 * <p>
 * Mulan Permissive Software License，Version 2
 * <p>
 * Mulan Permissive Software License，Version 2 (Mulan PSL v2)
 * January 2020 http://license.coscl.org.cn/MulanPSL2
 */
package com.walter.blog.business.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.walter.auth.SecurityUtil;
import com.walter.auth.config.user.BlogUser;
import com.walter.blog.business.content.service.CategoryService;
import com.walter.db.mapper.CategoryContentMapper;
import com.walter.db.mapper.CategoryMapper;
import com.walter.db.mapper.UserCategoryMapper;
import com.walter.db.pojo.Category;
import com.walter.db.pojo.CategoryContent;
import com.walter.db.pojo.UserCategory;
import com.walter.response.ResponseKit;
import com.walter.vo.category.CategoryListVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 分类 服务实现类
 * </p>
 *
 * @author wuchenxi
 * @since 2020-12-25
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Resource
    private HttpSession httpSession;

    @Resource
    private UserCategoryMapper userCategoryMapper;

    @Resource
    private CategoryContentMapper categoryContentMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseKit<Object> add(Category category) {
        if (StringUtils.isNotEmpty(category.getId())) {
            return this.edit(category);
        }

        BlogUser user = SecurityUtil.getBlogUser();
        int count = userCategoryMapper.countByUserIdAndCategoryName(user.getId(), category.getName());

        if (count > 0) {
            return ResponseKit.error(402, "您已有名称为《" + category.getName() + "》的分类，不能再次新增，请输入其他名称！");
        }

        category.setCreateTime(new Date());
        category.setUpdateTime(new Date());
        this.save(category);

        userCategoryMapper.insert(UserCategory.builder()
                .categoryId(category.getId())
                .createTime(new Date())
                .updateTime(new Date())
                .userId(user.getId())
                .build());

        return ResponseKit.success();
    }

    /**
     * 编辑分类
     *
     * @param category
     * @return
     */
    private ResponseKit<Object> edit(Category category) {
        BlogUser user = SecurityUtil.getBlogUser();
        UserCategory userCategory = userCategoryMapper.selectByUserIdAndCategoryId(user.getId(), category.getId());
        if (userCategory == null) {
            return ResponseKit.error(400, "修改分类出错！");
        }

        userCategory.setUpdateTime(new Date());
        userCategoryMapper.updateById(userCategory);

        Category category1 = this.getById(category.getId());
        category.setCreateTime(category1.getCreateTime());
        this.updateById(category);

        return ResponseKit.success();
    }

    @Override
    public ResponseKit<List<CategoryListVO>> listCategory() {
        BlogUser user = SecurityUtil.getBlogUser();
        List<CategoryListVO> vos = userCategoryMapper.selectByUserId(user.getId());
        return ResponseKit.success(vos);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseKit<Object> delete(String categoryId) {
        BlogUser user = SecurityUtil.getBlogUser();
        UserCategory userCategory = userCategoryMapper.selectByUserIdAndCategoryId(user.getId(), categoryId);
        if (userCategory == null) {
            return ResponseKit.error(400, "删除分类出错！该分类不属于当前用户！");
        }
        userCategoryMapper.delete(new LambdaQueryWrapper<UserCategory>().eq(UserCategory::getUserId, user.getId())
                .eq(UserCategory::getCategoryId, categoryId));

        this.removeById(categoryId);

        categoryContentMapper.delete(new LambdaQueryWrapper<CategoryContent>().eq(CategoryContent::getCategoryId, categoryId));

        return ResponseKit.success();
    }
}
